import request from '@/plugins/request'
import qs from 'qs'
import Setting from '@/setting'

export function GetTableList (apiUrl, type, data, isQs = false) {
  return request({
    url: Setting.apiBaseURL + apiUrl,
    method: type,
    data: data
  })
}

export function ApiRequest (apiUrl, type, data, isQs) {
  let config = {
    url: Setting.apiBaseURL + apiUrl + handleGetMenuParams(apiUrl),
    method: type,
    headers: {
      'Content-Type': isQs ? 'application/x-www-form-urlencoded' : 'application/json;charset=UTF-8',
    },
  }
  if (type === 'get') {
    config.params = data;
  } else {
    config.data = isQs ? qs.stringify(data) : data;
  }
  return request(config)
}

export function ApiRequestExportTable (apiUrl, type, data, isQs) {
  let config = {
    url: Setting.apiBaseURL + apiUrl + handleGetMenuParams(apiUrl),
    method: type,
    headers: {
      'Content-Type': isQs ? 'application/x-www-form-urlencoded' : 'application/json;charset=UTF-8',
    },
    responseType: 'arraybuffer' // 必须设置，不然导出的文件无法打开
  }
  if (type === 'get') {
    config.params = data;
  } else {
    config.data = isQs ? qs.stringify(data) : data;
  }
  return request(config)
}

/* 获取真实要传的menuId和btnId */
export const handleGetMenuParams = (apiUrl) => {
  let isSplit = []
  if (apiUrl) {
    isSplit = apiUrl.split('?')
  }
  let menuId = sessionStorage.getItem('menuId')
  let btnId = sessionStorage.getItem('buttonId')
  // if(!btnId) btnId = '2' // 默认查询传2
  let realBtnStr = (menuId && btnId) ? `menuId=${menuId}&buttonId=${btnId}` : ''
  let menuStr = `${isSplit.length > 1 ? `${realBtnStr ? ('&' + realBtnStr) : ''}` : `${realBtnStr ? '?' + realBtnStr : ''}`}`
  return menuStr
}
